<script setup lang="ts">
import TableTemplate from './components/TableTemplate.vue';
import BatchAddTemplate from './components/batchAddTemplate.vue';
import DialogTemplate from './components/dialogTemplate.vue';
import {ElMessage, ElMessageBox} from "element-plus";
import {
  batchAddAccount, checkResetPasswordById,
  deletesAccount,
  exportFileExcel,
  getPageAccountList, sendResetPasswordEmail,
  updateAccount
} from "../account/accountApi.js";
import {useUserStore} from "@/pinia/stores/user.ts";
const loading = ref(false)
const userData = useUserStore().userInfo
const ws = ref(null)
let dataSet = reactive({
  queryBox: [
    {
      model: 'username',
      type: 'input',
      placeholder: '请输入用户名称'
    },
    {
      model: 'sex',
      type:'select',
      placeholder: '请选择性别',
      options: [
        { label: '男', value: 0 },
        { label: '女', value: 1 },
        { label: '保密', value: 2 }
      ],
    },{
      model: 'status',
      type:'select',
      placeholder: '请账号选择状态',
      options: [
        { label: '启用', value: 0 },
        { label: '禁用', value: 1 },
      ],
    },
    {
      model: 'mobile',
      type: 'input',
      placeholder: '请输入手机号'
    }
  ],
  tableList: [
    {prop: 'username', label: '用户名', width: '150'},
    {prop: 'mobile', label: '手机号', width: '150'},
    {prop:'sex', label: '性别', width: '100'},
    {prop: 'email', label: '邮箱', width: '200'},
    {prop: 'creator', label: '创建者', width: '200'},
    {prop: 'createDate', label: '创建时间', width: '200'},
  ],
  tableListStutas: [
    {prop:'statuss', label: '状态', width: '120',stutasColor: 'danger'},
  ],
  tnQueryTop: [
    {name: '新增',click: 'userAdd', type: 'primary'},
    {name: '批量新增',click: 'userBatchAdd', type: 'primary'},
    {name: '批量删除',click: 'userBatchDelete', type: 'danger'},
    {name: '导出',click: 'userExport', type: 'primary'},
  ],
  operationBtns: [
    {name: '编辑', click: 'userEdit', type: 'primary'},
    {name: '删除', click: 'deleteId', type: 'danger'},
    {name: '详情', click: 'userDetail', type: 'info'},
    {name: '密码重置', click: 'resetPassword', type: 'warning'},
  ],
  tableData:{
    total: 0,
    rows: []
  }
})
//状态颜色
const getStatusColor = (data) => {
  switch (data) {
    case '启用':
      return 'success';
    case '禁用':
      return 'primary';
    default:
      return 'info';
  }
};
let batchAddVisible = reactive({
  fileName: '用户批量添加Excel模板.xlsx',
  dialogFormVisibles: false,
})
// 弹窗 数据
const registerDialogRef = ref(null)
const registerTableRef = ref(null)
const title = ref('用户新增')
const dialogTemplateRef = ref(null)
const dialogTemplateVisible = ref(false)
let formItems = [{
  list: [
    {
      label: '用户名',
      prop: 'username',
      type: 'input',
      rules: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 64, message: '长度在 3 到 64 个字符', trigger: 'blur' }
      ],
      placeholder: '请输入用户名'
    },
    {
      label: '手机号',
      prop: 'mobile',
      type: 'input',
      rules: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { min: 11, max: 11, message: '长度为11位', trigger: 'blur' }
      ],
      placeholder: '请输入手机号'
    },
    {
      label: '性别',
      prop:'sex',
      type:'select',
      options: [
        { label: '男', value: 0 },
        { label: '女', value: 1 }
      ],
      placeholder: '请选择性别'
    },
    {
      label: '邮箱',
      prop: 'email',
      type: 'input',
      rules: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
      ],
      placeholder: '请输入邮箱'
    },
    {
      label: '状态',
      prop: 'status',
      type: 'select',
      options: [
        {label: "启用", value: 0}
        ,{label: "禁用", value: 1}
      ],
      placeholder: '请选择状态'
    },
  ]
}]
// 表单数据
const initialData = ref({})
//查看为true，其他为false
const isViewMode = ref(false)
// 操作名称 新增，编辑 详情
const operationName = ref('')
const handleDialogSubmit = async (data) => {
  data.sex=="男"?data.sex=0:data.sex=1
  data.status=="启用"?data.status=0:data.status=1
  if (operationName.value === '新增'){
    data.occupation=1;
    await batchAddAccount([data]).then(res => {
      if (res.code === 0){
        ElMessage.success('新增成功')
        dialogTemplateVisible.value = false;
        dialogTemplateRef.value.dialogTemplateVisible = false;
        selectSubmit({ pageNum: 1, pageSize: 10 });
        return;
      }
      ElMessage.error(res.message || '新增失败')
    });
  }else {
    await updateAccount(data).then(res => {
      if (res.code === 0){
        ElMessage.success('编辑成功')
        dialogTemplateVisible.value = false;
        dialogTemplateRef.value.dialogTemplateVisible = false;
        selectSubmit({ pageNum: 1, pageSize: 10 });
        return;
      }
      ElMessage.error(res.message || '编辑失败')
    });
  }
}
// 重置
const resetSubmit = (data) => {
  selectSubmit(data);
}
// 查询
const selectSubmit = async (data) => {
  data.occupation=1;
  loading.value = true;
  await getPageAccountList(data).then(res => {
    dataSet.tableData.rows = res.data.records
    dataSet.tableData.total = res.data.total
  }).finally(() => {
    loading.value = false;
  });
}
//新增
const userAdd = () => {
  operationName.value = '新增'
  isViewMode.value = false
  title.value = '用户新增'
  initialData.value = {}
  dialogTemplateVisible.value = true;
  dialogTemplateRef.value.dialogTemplateVisible = true;
}
// 批量新增
const userBatchAdd = () => {
  batchAddVisible.dialogFormVisibles = true
}
const handleIndex = ref([])
const handleChange = (data) => {
  handleIndex.value = data
}
// 批量删除
const userBatchDelete = async () => {
  if (handleIndex.value.length === 0){
    ElMessage.error('请至少选择一条数据！')
    return;
  }
  ElMessageBox.confirm(
    '确定要删除这些项目吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    let ids = handleIndex.value.map(item => item.id)
    loading.value = true;
    await deletesAccount(ids).then(res => {
      if (res.code === 0){
        ElMessage.success('删除成功')
        registerTableRef.value?.clearSelection();
        selectSubmit({ pageNum: 1, pageSize: 10 });
        return;
      }
      ElMessage.error(res.message || '删除失败')
      registerTableRef.value?.clearSelection();
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除',
    })
  }).finally(() => {
    loading.value = false;
  })
}
// 导出
const userExport = () => {
  if (handleIndex.value.length < 1) {
    ElMessage.error("请选择要导出的数据！")
    return
  }
  exportFileExcel(handleIndex.value, '管理员');
  handleIndex.value = [];
  registerTableRef.value?.clearSelection();
}
// 编辑
const userEdit = (data) => {
  operationName.value = '编辑'
  isViewMode.value = false
  title.value = '用户编辑'
  initialData.value = { ...data }
  formItems =  [{
    list: [
      {
        label: '用户名',
        prop: 'username',
        type: 'input',
        disabled: true,
        placeholder: '请输入用户名'
      },
      {
        label: '手机号',
        prop: 'mobile',
        type: 'input',
        rules: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 11, max: 11, message: '长度为11位', trigger: 'blur' }
        ],
        placeholder: '请输入手机号'
      },
      {
        label: '性别',
        prop:'sex',
        type:'select',
        options: [
          { label: '男', value: 0 },
          { label: '女', value: 1 }
        ],
        placeholder: '请选择性别'
      },
      {
        label: '邮箱',
        prop: 'email',
        type: 'input',
        disabled: true,
        placeholder: '请输入邮箱'
      },
      {
        label: '状态',
        prop: 'status',
        type: 'select',
        options: [
          {label: "启用", value: 0}
          ,{label: "禁用", value: 1}
        ],
        placeholder: '请选择状态'
      },
    ]
  }]
  dialogTemplateVisible.value = true;
  dialogTemplateRef.value.dialogTemplateVisible = true;
}
// 删除
const deleteId = async (data) => {
  await deletesAccount([data.id]).then(res => {
    if (res.code === 0){
      ElMessage.success('删除成功')
      registerTableRef.value?.clearSelection();
      selectSubmit({ pageNum: 1, pageSize: 10 });
      return;
    }
    ElMessage.error(res.message || '删除失败')
  });
}
// 详情
const userDetail = (data) => {
  operationName.value = '详情'
  isViewMode.value = true
  title.value = '用户详情'
  initialData.value = { ...data }
  dialogTemplateVisible.value = true;
  dialogTemplateRef.value.dialogTemplateVisible = true;
}
// 批量新增提交
const batchAddSubmit = async (fileList, username) => {
  // 必须包含的字段
  const requiredFields = ["用户名", "手机号", "性别", "邮箱", "状态"];

  // 检查 fileList 的字段
  const isValidFile = fileList.every(item =>
    requiredFields.every(field => Object.prototype.hasOwnProperty.call(item, field))
  );

  if (!isValidFile) {
    ElMessage.error("文件格式错误，请上传正确的模板文件！");
    return;
  }
  // 构造数据
  const data = fileList.map(item => ({
    username: item.用户名,
    mobile: item.手机号,
    sex: item.性别=="男"?0:1,
    email: item.邮箱,
    status: item.状态=== "启用"?0:1,
    creator: username,
    occupation: 1,
  }));

  if (data.length < 1) {
    ElMessage.error("文件内容为空，请检查模板文件！");
    return;
  }
  //批量新增
  let response = await batchAddAccount(data);
  if (response.code === 0) {
    ElMessage.success("批量新增成功");
    batchAddVisible.dialogFormVisibles = false;
    selectSubmit({});
    return;
  }
  ElMessage.error(response.message || "批量新增失败，请检查表单");
};
const resetPassword = async (data) => {
  // 发送请求，请求用户是否同意重置密码
  await checkResetPasswordById(data.id).then(async res => {
    if (res.data==1){
      handleResetPassword(data.id);
      return;
    }else if (res.data==0){
      // 发送请求，请求重置密码
      let response = await sendResetPasswordEmail(data,userData.id);
      if (response.code === 0) {
        ElMessage.success("请求发送成功，请等待用户回应");
        return;
      }else {
        ElMessage.error(response.message || "请求发送失败");
      }
    }
  })
}
const handleResetPassword = async (userId) => {
  let response = await updateAccount({ id: userId, password: '123456',isReset: 0 });
  if (response.code === 0) {
    ElMessage.success("密码重置成功");
    return;
  }
  ElMessage.error(response.message || "密码重置失败");
}

const ljie = () => {
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    return;
  }
  ws.value = new WebSocket(`ws://localhost:8082/userReset/${userData.id}`);
  ws.value.onopen = (event) => {

  };
  ws.value.onerror = (error) => {
    console.error("WebSocket error:", error);
  };
  ws.value.onclose = (event) => {

  };
  ws.value.onmessage = (event) => {
    try {
      const message = JSON.parse(event.data);
      openResetPassword(message.split(":")[1],message.split(":")[0],parseInt(message.split(":")[2]))
    } catch (error) {
      console.error("消息解析失败:", error);
    }
  };
}

const openResetPassword = (isReset, username, userId) => {
  ElNotification({
    title: '提示',
    message: '用户 '+username + (isReset==='1'?'已同意重置密码，点击重置':'未同意重置密码'),
    type: isReset==='1'?'success':'error',
    onClick: () => {
      if (isReset==='1'){
        handleResetPassword(userId)
      }
    }

  })
}
onMounted(() => {
  ljie();
  selectSubmit({ pageNum: 1, pageSize: 10})
})
</script>

<template>
  <div class="container">
    <TableTemplate
      ref="registerTableRef"
      :data-set="dataSet"
      @userAdd="userAdd"
      @userEdit="userEdit"
      :getStatusColor="getStatusColor"
      @deleteId="deleteId"
      @userDetail="userDetail"
      @resetPassword="resetPassword"
      @userBatchDelete="userBatchDelete"
      @userBatchAdd="userBatchAdd"
      @reset-submit="resetSubmit"
      @userExport="userExport"
      @handleChange="handleChange"
      @select-submit="selectSubmit"
      :loading="loading"
    />
    <BatchAddTemplate
      ref="registerDialogRef"
      v-model="batchAddVisible.dialogFormVisibles"
      @submit-adds="batchAddSubmit"
      @userBatchAdd="userBatchAdd"
      :batch-add-visible="batchAddVisible"
    />
    <DialogTemplate
      v-model="dialogTemplateVisible"
      ref="dialogTemplateRef"
      :title="title"
      :width="'500px'"
      :initial-data="initialData"
      :form-items="formItems"
      :is-view="isViewMode"
      @handleDialogSubmit="handleDialogSubmit"
      :operation-name="operationName"
    />
  </div>

</template>

<style scoped lang="scss">

</style>
